/**
 * Created by MyPC on 2017/6/18.
 */
let express = require('express');
let router = express.Router();
let resultJson = require('../../common/resultJson');
let tagsDao = require('../dao/tags');

router.get('/listByAll', function (req, res, next) {
  let promise = tagsDao.listByAll();
  promise.then(function (results, fields) {
    res.json(resultJson.create(1, 'success', results));
  }).catch(function (err) {
    console.log(err);
    res.json(resultJson.create('系统繁忙,请稍后再试'))
  })

})
// 新增
router.post('/', function (req, res, next) {
  let names = req.body.names;
  if(typeof names !== 'string' && names.length <= 0){
    res.json(resultJson.create('请输入内容'));
    return;
  }
  let promise = tagsDao.save({names});
  promise.then(function (results, fields) {
    res.json(resultJson.create(1, '保存成功', results.insertId));
  }).catch(function (err) {
    console.log(err);
    res.json(resultJson.create('系统繁忙,请稍后再试'))
  })
})
// 修改
router.put('/:id', function (req, res, next) {
  let params = {};
  let names = req.body.names;
  let id = Number(req.params.id);
  if(!(id>0)){
    res.json(resultJson.create('请选择有效的标签修改'));
    return;
  }else{
    params.id = id;
  }
  if (typeof names === 'string' && names.length > 0) {
    params.names = names;
  } else {
    res.json(resultJson.create('请填写标签名'));
    return;
  }
  var promise = tagsDao.updateById(params)
  promise.then(function (results, fields) {
    if(results.changedRows>0){
      res.json(resultJson.create(1, 'success', results.changedRows));
    }else{
      res.json(resultJson.create('修改失败'));
    }
  }).catch(function (err) {
    console.log(err);
    res.json(resultJson.create('系统繁忙,请稍后再试'))
  })
})
// 删除
router.delete('/:id', function (req, res, next) {
  let id = Number(req.params.id);
  if(!(id>0)){
    res.json(resultJson.create('请选择有效的标签删除'));
    return;
  }
  let promise = tagsDao.removeById(id);
  promise.then(function (results, fields) {
    if(results.changedRows>0){
      res.json(resultJson.create(1, 'success', results.changedRows));
    }else{
      res.json(resultJson.create('删除失败'));
    }
  }).catch(function (err) {
    console.log(err);
    res.json(resultJson.create('系统繁忙,请稍后再试'))
  })
})

module.exports = router;
